import { getUserInfo } from "@/api/login";
import { defineStore } from "pinia";

export const useUserStore = defineStore('user', {
    state: () => {
        return { 
            token: '',
            userInfo: '',
        }
    },
    actions: {
        setToken(token) {
            this.token = token;
        },
        clearToken() {
            this.token = '';
            this.userInfo = '';
            localStorage.removeItem('txmabc_user');
        },
        setUserInfo(userInfo) {
            this.userInfo = userInfo;
        },
        requestUserInfo() {
            return new Promise((resolve, reject) => {
              getUserInfo().then(async response => {
                if (! response || ! response.data) {
                  this.clearToken()
                  await router.push({name: 'login'})
                  reject(false)
                } else {
                  this.setInfo(response.data)
                  resolve(response.data)
                }
              })
            })
          },
    },
    getters: {
        isAuthenticated: (state) =>!!state.token,
    },
    persist: {
        enabled: true,
        strategies: [{
            key: 'txmabc_user',
            storage: localStorage,
        }]
    }
});